//
//  SettingViewController.m
//  GameBaby
//
//  Created by keyZhang on 13-12-19.
//  Copyright (c) 2013年 keyZhang. All rights reserved.
//

#import "SettingViewController.h"
#import "MoreTableHeaderView.h"
#import "MoreTableVIewCell.h"
#import "CKXViewController.h"
#import "SDImageCache.h"
#import "AboutUsViewController.h"
#import "FeedBackViewController.h"
#import "DataService.h"
#import "OpenUDID.h"
#import "MessageViewController.h"

@interface SettingViewController ()
{
    NSArray *_titleName;
    NSArray *_imgName;
}

@end

@implementation SettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UILabel *t = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        t.font = [UIFont systemFontOfSize:16];
        t.textColor = [UIColor blackColor];
        t.backgroundColor = [UIColor clearColor];
        t.textAlignment = UITextAlignmentCenter;
        t.text = @"更多";
        self.navigationItem.titleView = t;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _titleName = @[@"存卡箱",@"消息",@"意见反馈",@"喜欢我们，打分鼓励",@"关于我们",@"每日签到",@"清空缓存"];
    _imgName = @[@"zjxqx2_03.png",@"zjxqx2_11.png",@"zjxqx2_18.png",@"zjxqx2_20.png",@"zjxqx2_22.png",@"zjxqx2_06.png",@"zjxqx2_24.png"];
    
//    [self performSelector:@selector(viewWillAppear:) withObject:Nil afterDelay:.5];
}

- (void)_countCacheSize
{
    sum = 0;
    //拿到缓存文件的目录
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/ImageCache"];
    //计算大小
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //图片名字的集合
    NSArray *filePaths = [fileManager subpathsOfDirectoryAtPath:path error:nil];
    for (NSString *subPath in filePaths) {
        //图片的路径
        NSString *filePath = [path stringByAppendingPathComponent:subPath];
        //获取文件的属性
        NSDictionary *dic = [fileManager attributesOfItemAtPath:filePath error:nil];
        long long size = [dic fileSize];
        sum += size;
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MoreTableVIewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"MoreTableVIewCell" owner:self options:nil] lastObject];
    cell.headImgView.image = [UIImage imageNamed:_imgName[indexPath.row]];
    cell.titleLabel.text = _titleName[indexPath.row];
    
    if (indexPath.row == _titleName.count - 1) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(210, 12, 70, 20)];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentRight;
        label.backgroundColor = [UIColor clearColor];
        float m = sum /(1024.0 * 1024.0);
        label.text = [NSString stringWithFormat:@"%.1fM",m];

        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell.contentView addSubview:label];
    }
    
    if (indexPath.row == _titleName.count - 2) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(180, 12, 100, 20)];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentRight;
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor darkGrayColor];
        
        
        label.tag = 1424;

        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"is_sign"]intValue] == 0) {
            label.text = [NSString stringWithFormat:@"未签到"];
        }else if([[[NSUserDefaults standardUserDefaults]objectForKey:@"is_sign"]intValue]  == 1)
        {
            label.text = [NSString stringWithFormat:@"已签到"];
        }

        
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell.contentView addSubview:label];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.moreTbView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        CKXViewController *ckxVC = [[CKXViewController alloc] init];
        [self.navigationController pushViewController:ckxVC animated:YES];
        return;
    }
    
    if (indexPath.row == 1) {
        MessageViewController *messageVC = [[MessageViewController alloc] init];
        [self.navigationController pushViewController:messageVC animated:YES];
        return;
        
    }
    
    if (indexPath.row == 2) {
        FeedBackViewController *feedBackVC = [[FeedBackViewController alloc] init];
        [self.navigationController pushViewController:feedBackVC animated:YES];
        return;
    }
    
    if (indexPath.row == 3) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[UIDevice currentDevice].systemVersion floatValue] >= 7.0f? @"itms-apps://itunes.apple.com/app/id841721856": @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=841721856"]];
        return;
    }
    
    if (indexPath.row == 4) {
        AboutUsViewController *aboutUsVC = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:aboutUsVC animated:YES];
        return;
    }
    
    if (indexPath.row == 5) {
        UILabel *signLabel = (UILabel *)[self.view viewWithTag:1424];
        if ([signLabel.text isEqualToString:@"未签到"]) {
            signLabel.text = @"已签到";
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"is_sign"];
            [self.moreTbView reloadData];
//           获取签到信息,从而实时改变wnd
            [self performSelector:@selector(getSignMesg) withObject:nil afterDelay:.5];

        }
        if ([signLabel.text isEqualToString:@"已签到"]) {
            NSString *urlStr = [NSString stringWithFormat:@"http://m.a.ewoka.com/user/sign"];
            NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[[NSUserDefaults standardUserDefaults] objectForKey:@"appid"],@"appid", nil];
            __weak SettingViewController *this = self;
            [DataService requestWithURL:urlStr
                                 params:mDic
                             httpMethod:@"POST"
                            finishBlock:^(id result) {
                                [this loadDataFinished:result];
                            }];

        }
        return;
    }

    
    if (indexPath.row == 6) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"清除缓存"
                                                       message:@"确定要清除么"
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                             otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
}

//未签到变成已签到时获取个人签到的信息,然后实时改变wnd
- (void)getSignMesg
{
    NSString *urlStr = [NSString stringWithFormat:@"http://m.a.ewoka.com/user"];
    NSString *devicePlatForm = [(AppDelegate *)[UIApplication sharedApplication].delegate doDevicePlatform];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[[NSUserDefaults standardUserDefaults] objectForKey:@"appid"],@"appid",devicePlatForm,@"client", nil];
    __weak SettingViewController *this = self;
    [DataService requestWithURL:urlStr
                         params:dic
                     httpMethod:@"POST"
                    finishBlock:^(id result) {
                        [this loadSignDataFinished:result];
                    }];
}

- (void)loadDataFinished:(NSDictionary *)result
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[result objectForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [self viewWillAppear:YES];
    [alert show];
}

- (void)loadSignDataFinished:(NSDictionary *)result
{
    self.moreTbheadView.wjWndLabel.text = [NSString stringWithFormat:@"剩余蜗牛蛋：%@个",[result objectForKey:@"wnd"]];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"wnd"] forKey:@"wnd"];
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        //清除缓存
        [[SDImageCache sharedImageCache] clearDisk];
        [[SDImageCache sharedImageCache] clearMemory];
        [self _countCacheSize];
        //刷新tableView
        [self.moreTbView reloadData];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    self.moreTbheadView = [[[NSBundle mainBundle] loadNibNamed:@"MoreTableHeaderView" owner:self options:nil] lastObject];
    self.moreTbheadView.headImgBtn.userInteractionEnabled = NO;
    self.moreTbheadView.editLabel.hidden = YES;
//    头像设置
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"headImgData"];
    if (data) {
        UIImage *headImage = [UIImage imageWithData:data];
        UIImage *newImg = [self circleImage:headImage withParam:1];
        [self.moreTbheadView.headImgBtn setBackgroundImage:newImg forState:UIControlStateNormal];
    }
    self.moreTbView.tableHeaderView = self.moreTbheadView;
    
//    刷新一下
    [self.moreTbView reloadData];
    
    [super viewWillAppear:animated];
    //计算缓存的大小
    [self _countCacheSize];
//    [self.moreTbView reloadData];
}

//使img变圆形
-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
    UIGraphicsBeginImageContext(image.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
	CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
	CGContextAddEllipseInRect(context, rect);
	CGContextClip(context);
	
	[image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
	CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

@end
